package com.example.demo.controller;

import com.example.demo.Result;
import com.example.demo.Utils.JwtUtil;
import jakarta.annotation.Resource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@RestController
public class loginController {
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private JwtUtil jwtUtil;

    @GetMapping("/login")
    public Result login(String phone, String pwd) {
        try {
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(phone, pwd);
            Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
            if (Objects.isNull(authenticate)) {
                return Result.error("账户或密码错误!");
            }
            String token=jwtUtil.generateToken(authenticate);
            return Result.success(token);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return Result.error("遇到未知错误!");
        }
    }
}
